import numpy as np
from math import sqrt
from collections import Counter

# 对象的形式 整理 和同名的效果其实一样
class KNNClassifier:

    def __init__(self, k):
        """初始化kNN分类器"""
        assert k >= 1, "k must be valid"
        self.k = k
        # 下划线就是私有
        self._X_train = None
        self._y_train = None


    def fit(self, X_train, y_train):
        """根据训练数据集X_train和y_train训练kNN分类器
        :param X_train: 特征值矩阵
        :type y_train: 结果列向量
        """
        # 样本个数(行数)匹配
        assert X_train.shape[0] == y_train.shape[0], \
            "the size of X_train must be equal to the size of y_train"
        # 有那么多样本
        assert self.k <= X_train.shape[0], \
            "the size of X_train must be at least k."

        self._X_train = X_train
        self._y_train = y_train
        return self

    def predict(self, X_predict):

        """给定待预测数据集X_predict，返回表示X_predict的结果向量"""
        assert self._X_train is not None and self._y_train is not None, \
            "must fit before predict!"

        # 列数一致
        assert X_predict.shape[1] == self._X_train.shape[1], \
            "the feature number of X_predict must be equal to X_train"

        y_predict = [self._predict(x) for x in X_predict]
        return np.array(y_predict)

    # 私有函数
    def _predict(self, x):

        # 特征个数合法
        """给定单个待预测数据x，返回x的预测结果值"""
        assert x.shape[0] == self._X_train.shape[1], \
            "the feature number of x must be equal to X_train"

        distances = [sqrt(np.sum((x_train - x) ** 2))
                     for x_train in self._X_train]
        nearest = np.argsort(distances)  # 距离排序 结果是索引

        # 拿到前k的索引对应的结果
        topK_y = [self._y_train[i] for i in nearest[:self.k]]
        votes = Counter(topK_y)  # 统计各结果数量

        return votes.most_common(1)[0][0]  # 第一的结果

    # 显示函数
    def __repr__(self):
        return "KNN(k=%d)" % self.k
